#!/usr/bin/python
# -*- coding: utf-8 -*-
# File: clipboard.py
# Author: Tomás Vírseda
# License: GPL v3
# Description: Clipboard manager for Vazaar
# FIXME: this is very very tacky. Support more targets. It won't work with multiple paths

import os
import gobject

import gtk

from vazaarlib.namespaces import NFO

from vazaarlib.utils import get_logger
from vazaarlib.constants import SCHEMES_WHITELIST

class ClipboardManager():
    def __init__(self, gui):
        self.gui = gui
        self.app = gui.app
        self.log = get_logger("Clipboard")
        display = gtk.gdk.display_manager_get().get_default_display()
        self.clipboard = gtk.Clipboard(display, "CLIPBOARD")
        #self.clipboard = gtk.Clipboard()
        self.timeout = None
        self.data = ""
        self.gui.settings['Clipboard'] = {}
        self.get_settings()
        status = bool(self.gui.settings['Clipboard']['chk-monitoring'])
        if status == True:
            self.log.info("Monitoring clipboard")
            self.install_timeout()
        else:
            self.uninstall_timeout()


    def uninstall_timeout(self):
        """ stop clipboard monitoring """
        try:
            self.log.info("Stop monitoring clipboard")
            icon = self.gui.icons.get_icon_by_name(NFO['Clipboard'], 128, 128)
            self.gui.actions.notify("Stop monitoring clipboard", "<big><b>Vazaar</b> stopped <i>monitoring</i> your clipboard", icon)
            gobject.source_remove(self.timeout)
        except:
            # First time there is no hook if clipboar monitoring is stopped
            pass

    def install_timeout(self):
        """ allow clipboard monitoring  """
        self.log.info("Monitoring clipboard")
        icon = self.gui.icons.get_icon_by_name(NFO['Clipboard'], 128, 128)
        self.gui.actions.notify("Monitoring clipboard", "<big><b>Vazaar</b> is <i>monitoring</i> your clipboard for <i>new resources</i>", icon)
        self.timeout = gobject.timeout_add(500, self.check)

    def check(self):
        """Check if clipboard changes every 1000 miliseconds.
        Targets: 'TIMESTAMP', 'TARGETS', 'MULTIPLE', 'SAVE_TARGETS',
        'GTK_TEXT_BUFFER_CONTENTS', 'application/x-gtk-text-buffer-rich-text',
        'UTF8_STRING', 'COMPOUND_TEXT', 'TEXT', 'STRING',
        'text/plain;charset=utf-8', 'text/plain;charset=UTF-8', 'text/plain')
        """

        self.clipboard.request_text(self.add)

        return True

    def is_directory(self, dir):
        return os.path.isdir(dir)

    def add(self, clipboard, text, data):
        """Add data from clipboard to Vazaar"""

        #print clipboard, text, data
        if not text:
            return

        if len(self.data) == 0:
            # Initialize Clipboard
            self.data = unicode(text)
            #self.gui.actions.add_resource((self.data,))
            return

        if self.data != text:
            self.data  = text
            if not self.is_directory(text):
                self.log.debug("adding new resource")
                scheme = self.data.split(':')[0]
                try:
                    wlscheme = SCHEMES_WHITELIST[scheme]
                    self.gui.actions.add_resource((text,))
                except:
                    if os.path.isfile(text):
                        self.gui.actions.add_resource((text,))
                    else:
                        sep = text.find(':')
                        text = text[0:sep] + ' : ' + text[sep+1:]
                        self.gui.actions.add_resource((text,))
            else:
                #self.gui.actions.add_resource((text,))
                self.gui.actions.update_statusbar("<b>Adding directories from clipboard is not allowed. Add them manually.</b>")
                self.log.warning("Adding directories from clipboard is not allowed. Add them manually.")

    def get_settings(self):
        try:
            self.gui.settings['Clipboard']['chk-monitoring'] = self.app.cfgmgr.get_value('Clipboard', 'chk-monitoring')
            #self.log.debug("Reading clipboard settings from config file")
        except Exception, error:
            self.save_default_settings()


    def save_default_settings(self):
        try:
            self.app.cfgmgr.set_value('Clipboard', 'chk-monitoring', self.gui.settings['Clipboard']['chk-monitoring'])
            self.app.cfgmgr.write_config()
        except Exception, error:
            # First time Vazaar is executed or vazaar.conf doesn' exists
            # clipboard settings aren't set
            self.gui.settings['Clipboard']['chk-monitoring'] = True
            self.app.cfgmgr.set_value('Clipboard', 'chk-monitoring', self.gui.settings['Clipboard']['chk-monitoring'])
            self.app.cfgmgr.write_config()

